package de.koller.worlders.engine.entity.zone;

import de.koller.worlders.engine.entity.mo.MovingObject;
import de.koller.worlders.engine.tiles.ITile;
import de.koller.worlders.engine.tiles.data.ITileCreator;
import de.koller.worlders.engine.tiles.data.MapDetails;
import de.koller.worlders.render.VisualMap;
import de.koller.worlders.render.visual.DisplayRenderObject;

public class HelpZone extends ZoneEffect {
	public static final int GEN_ID = 5;
	
	public static final ITileCreator GEN_INSTANCE = new ITileCreator() {
		@Override public ITile newInstance() {
			return new Zone().addEffect( new HelpZone() );
		}
		
		@Override public DisplayRenderObject getIcon() { return VisualMap.help; }
		@Override public String getName() { return "Hilfe"; }
	};
	
	private boolean showHelp = false;
	private String currentText = "";
	
	protected HelpZone() {}
	
	@Override
	public void init( Zone z ) {
		super.init( z );
		
//		z.setTextureRep( new TextureRep( "data/tiles.png", 32, 0, 32, 32 ) );
		z.getTile().setVisual( VisualMap.help );

	}
	
	@Override
	public void enter( MovingObject mo ) {
		if( mo.mostate.isGameplayAffected() == false )
			return;
		
		showHelp = true;
		
		redefine();
		String text = getHelpText();
		if( text == null ) {
			redefine();
			text = getHelpText();
		}

		if( text == null )
			currentText = "Kein Text definiert!";
		else
			currentText = text;
	}

	@Override
	public void leave( MovingObject mo ) {
		if( mo.mostate.isGameplayAffected() ) {
			zone.root.getGui().getMessage().unShow();
			showHelp = false;
		}
	}

	@Override
	public void in( MovingObject mo ) {
		super.in( mo );
		
		renderIN();
	}
	
	private void renderIN() {
		if( !showHelp )
			return;
		
		String t = currentText;
		zone.root.getGui().getMessage().show( t );
	}

	private String getHelpText() {
		MapDetails d = zone.root.getTileMap().tileHolder.getDetail( zone.getPosition().getXi(), zone.getPosition().getYi() );
		MapDetails.DetailEntity mld = d.getDetail( MapDetails.IDEntity.HelpTile,
				zone.getPosition().getXi(), zone.getPosition().getYi() );
		
		if( mld == null )
			return null;
		else
			return mld.content;
	}
	
	private void redefine() {
		String n = zone.root.getGui().getConsoleInput().getContent();
		if( n.startsWith( "helpText " ) ) {
			n = n.replaceAll( "helpText ", "" );
			zone.root.getGui().getConsoleInput().clearConent();
		} else
			return;
		
		int x = zone.getPosition().getXi();
		int y = zone.getPosition().getYi();
		MapDetails d = zone.root.getTileMap().tileHolder.getDetail( zone.getPosition().getXi(), zone.getPosition().getYi() );
		
		d.removeDetail( MapDetails.IDEntity.HelpTile, x, y );
		
		d.addDetail( MapDetails.IDEntity.HelpTile, x, y, n );
	}
}
